package com.hot12345.common.freemarker;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;

import com.hot12345.common.spring.ApplicationContextUtil;
import com.hot12345.common.spring.SpringFreeMarkerManagerInit;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMarkerManager {

	private static final Log logger = LogFactory.getLog(FreeMarkerManager.class);
	private Configuration cfg; 
	private static FreeMarkerManager frm=new FreeMarkerManager();
	
	private FreeMarkerManager(){
		   
	}
	//工厂模式实现single,
	 public static  FreeMarkerManager  getInstance(){
		 return frm;
	 }
	 
	 public void setConfiguration(String templatePath) {
         //设置freemarker的参数
         cfg = new Configuration();
         try {
        	File filePath = new File(templatePath);// 是否会造成覆盖?
			cfg.setDirectoryForTemplateLoading(filePath);
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			cfg.setDefaultEncoding("UTF-8");
			cfg.setOutputEncoding("UTF-8");
			cfg.setLocale(Locale.CHINA);
			cfg.setNumberFormat("#.###");// 数字格式化，最多保留三位小数
			cfg.setDateFormat("yyyy-MM-dd");
			cfg.setTimeFormat("HH:mm:ss");
			cfg.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
         } catch (IOException ex) {
            	ex.printStackTrace();
         }
     }

	 /** 
      * 生成静态文件. 
      * 
      * @param templateFileName 模板文件名,相对htmlskin路径,例如"/tpxw/view.ftl" 
      * @param propMap 用于处理模板的属性Object映射 
      * @param htmlFilePath 要生成的静态文件的路径,相对设置中的根路径,例如 "/tpxw/1/2005/4/" 
      * @param htmlFileName 要生成的文件名,例如 "1.htm" 
      */ 
	 /**
	  * 
	  * @param templatePath 模板路径
	  * @param templateFileName 模板名称
	  * @param dataMap Map类型的数据对象 
	  * @param htmlFilePath 生成html的路径
	  * @param htmlFileName 生成html的文件名称
	  * @return 
	  * @author wuzongbao
	  * @date 2012-7-11 下午03:03:13
	  */
     public boolean createHtmlFile(String templatePath, String templateFileName,Map<String,Object> dataMap, String htmlFilePath,String htmlFileName) {
    	 String str = "WEB-INF/classes";
    	 String classPath = FreeMarkerManager.class.getResource("").getPath();
		 classPath = classPath.substring(0, classPath.indexOf(str));
		 // String classesPath = classPath+str;
		 // ApplicationContext ac = new
		 // FileSystemXmlApplicationContext(classesPath+"/applicationContext.xml");
		 // SpringFreeMarkerManagerInit fmk =
		 // (SpringFreeMarkerManagerInit)ac.getBean("freemarkerConfig");
		 ApplicationContext context = ApplicationContextUtil.getContext();
		 SpringFreeMarkerManagerInit fmk = (SpringFreeMarkerManagerInit) context.getBean("freemarkerConfig");
		 // SpringFreeMarkerManagerInit fmk = new SpringFreeMarkerManagerInit();
		
		 if (fmk == null) {
			// throw new Exception("fmk==null");
			 logger.error("获取freemarker配置类失败");
		 	return false;
		 }
		 cfg = fmk.getConfiguration();
		 try {
			// logger.error("templateFileName="+templateFileName);
			 Template t = cfg.getTemplate(templateFileName);
		
			 // web目录
			 // String getPath = getClass().getResource("/").getPath();
			 // getPath = getPath.replace("/WEB-INF/classes/", "");
			
			 htmlFilePath = classPath + htmlFilePath;
			 // logger.error("FreeMarkManager.htmlFilePath======"+htmlFilePath);
			 // 创建存放静态html页面的路径
			 creatFileDir(htmlFilePath);
			
			 File htmlFile = new File(htmlFilePath + "/" + htmlFileName);
			
			 Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile)));
			 // 生成html
			 t.process(dataMap, out);
			 logger.info("craete html file success,file:" + htmlFile);
		 } catch (TemplateException e) {
		 	logger.error("Error while processing FreeMarker template "
					+ templateFileName, e);
			return false;
		 } catch (IOException e) {
			logger.error("Error while generate Static Html File "
					+ htmlFileName, e);
			return false;
		 }
		
		return true; 
     }

     
      
      public static boolean creatFileDir(String dir){
    	  File file = new File(dir);
    	  if(file==null){
    		  return false;
    	  }
    	  // 文件夹不存在则创建
    	  if(!file.exists()){
    		  file.mkdirs();
    		  return true;
    	  }
    	  return true;
      }
}
